import { isObject } from "lodash";
import { transformlat, transformlng } from "./latlng";
const wgs84togcj02Arr = (arr: number[]) => {
  const [lng, lat] = arr;

  const a = 6378245.0;
  const ee = 0.00669342162296594323;
  const PI = 3.1415926535897932384626;

  let dlat = transformlat(lng - 105.0, lat - 35.0);
  let dlng = transformlng(lng - 105.0, lat - 35.0);
  let radlat = (lat / 180.0) * PI;
  let magic = Math.sin(radlat);
  magic = 1 - ee * magic * magic;
  let sqrtmagic = Math.sqrt(magic);
  dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI);
  dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI);
  const mglat = Number(lat) + Number(dlat);
  const mglng = Number(lng) + Number(dlng);
  return [mglng, mglat];
};

const tranform = (obj: any) => {
  for (const key in obj) {
    if (key === "features") {
      if (Array.isArray(obj[key])) {
        obj[key].forEach((item: any) => {
          item.geometry.coordinates = item.geometry.coordinates.map(
            (itemm: any) => itemm.map((itemmm: any) => wgs84togcj02Arr(itemmm))
          );
        });
      }
    }
  }
};
/**
 *
 * @param obj
 */
export const wgs84togcj02 = (obj: object | undefined) => {
  if (!obj) return {};
  //拷贝原始对象
  let newObj = JSON.parse(JSON.stringify(obj));
  // 原始坐标
  if (isObject(newObj)) {
    tranform(newObj);
    return newObj;
  } else {
    return {};
  }
};
